package com.school.controller.admin;


import com.github.pagehelper.PageInfo;
import com.school.exception.EmailWrongFormatException;
import com.school.exception.UsernameNullPointerException;
import com.school.model.User;
import com.school.model.UserRole;
import com.school.service.impl.EmailServiceImpl;
import com.school.service.impl.UserRoleServiceImpl;
import com.school.service.impl.UserServiceImpl;
import com.school.utils.AssertUtil;
import com.school.utils.ResponseUtil;
import com.school.utils.RoleEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Api(
        value = "系统参数配置",
        tags = {"系统参数配置"}
)
@RestController
@RequestMapping({"/api/admin/sys"})

public class AdminSystemController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    EmailServiceImpl emailService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    UserRoleServiceImpl userRoleService;

    @ApiOperation(value = "配置系统邮箱", notes = "配置系统邮箱")
    @PreAuthorize("hasRole('ADMINISTRATOR')")
    @PostMapping("/sysConfig")
    public Object sysConfig(@ApiParam(example = "123@qq.com", value = "系统邮箱账号") @RequestParam(value = "username", required = false) String username,
                            @ApiParam(example = "123456", value = "开启POP3后获得的授权码") @RequestParam(value = "code", required = false) String code,
                            HttpServletRequest request) throws EmailWrongFormatException, UsernameNullPointerException {
        if (StringUtils.hasText(username) && StringUtils.hasText(code)) {
            modifySystemEmail(username, code, request);
            return ResponseUtil.build(HttpStatus.OK.value(), "系统配置成功！");
        }
        return ResponseUtil.build(HttpStatus.BAD_REQUEST.value(), "系统邮箱账号或授权码不能为空！");
    }

    private void modifySystemEmail(@ApiParam(example = "123@qq.com", value = "系统邮箱账号") @RequestParam("username") String username,
                                   @ApiParam(example = "123456", value = "开启POP3后获得的授权码") @RequestParam("code") String code,
                                   HttpServletRequest request) throws EmailWrongFormatException, UsernameNullPointerException {
        logger.info("[" + request.getRemoteAddr() + "] 管理员修改默认系统邮箱！");
        Assert.notNull(code, "管理端设置系统的邮箱的授权码不应为空！");
        AssertUtil.isValidMail(username, "设置的系统邮箱不能为空！");
        emailService.modifySystemEmail(username, code);
        ResponseUtil.build(HttpStatus.OK.value(), "修改系统邮箱成功！");
    }

    @GetMapping("/sysConfig")
    @ApiOperation(value = "获取系统邮箱配置", notes = "获取系统邮箱配置")
    @PreAuthorize("hasRole('ADMINISTRATOR')")
    public Object retrieveSysConfig() {
//        emailService.modifySystemEmail;
        EmailServiceImpl.EmailInfo emailInfo = emailService.retrieveSystemEmailInfo();
        return ResponseUtil.build(HttpStatus.OK.value(), "获取系统设置成功！", emailInfo);
    }

    @PostMapping("/clean")
    @ApiOperation(value = "清除数据", notes = "清除所有数据")
    @PreAuthorize("hasRole('ADMINISTRATOR')")
    public String cleanData() {
        PageInfo<User> userPageInfo = userService.querySelective(User.Column.id, User.Column.username);
        List<User> users = userPageInfo.getList();
        for (User user : users) {
            List<UserRole> userRoles = userRoleService.queryByUserId(user.getId());
            if (userRoles.size() != 0) {
                Set<Integer> roles = new HashSet<>();
                for (UserRole userRole : userRoles) {
                    roles.add(userRole.getRoleId());
                }
                if(roles.contains(RoleEnum.ADMINISTRATOR.value())){
                    continue;
                }
                userService.deleteById(user.getId());
            }
        }
        return ResponseUtil.build(HttpStatus.OK.value(), "删除所有数据成功！");
    }


}
